package com.arcaneshift.servlet.action.game;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.arcaneshift.model.action.game.Player;
import com.arcaneshift.model.request.LeaveQueuePlayerRequest;
import com.arcaneshift.model.response.LeaveQueuePlayerResponse;
import com.arcaneshift.model.validators.QueuePlayerValidator;
import com.arcaneshift.model.validators.system.SessionValidator;
import com.arcaneshift.security.errors.PlayerError;
import com.arcaneshift.servlet.util.network.RequestAction;
import com.arcaneshift.servlet.util.parser.LeaveQueuePlayerXMLParser;
import com.arcaneshift.util.PlayerCacheContainer;
import com.common.model.abstracts.AbstractRequest;
import com.common.model.abstracts.AbstractValidator;
import com.common.model.validators.ActionValidator;
import com.common.security.errors.ParserError;
import com.common.security.exceptions.ParserException;
import com.common.servlet.abstracts.AbstractParserServlet;
import com.common.servlet.interfaces.IParser;

public class LeaveQueuePlayerServlet extends AbstractParserServlet {
	private static final long serialVersionUID = 1L;
	private static Set<AbstractValidator> validators = new HashSet<AbstractValidator>();
	
	private LeaveQueuePlayerRequest requestContent;
	private LeaveQueuePlayerXMLParser parser = new LeaveQueuePlayerXMLParser();
	
	static {
		validators.add(new ActionValidator(RequestAction.LEAVE_QUEUE_PLAYER));
		validators.add(new SessionValidator());
		validators.add(new QueuePlayerValidator());
	}

	@Override
	public void handle(HttpServletRequest request, HttpServletResponse response) {
		try {
			LeaveQueuePlayerResponse leaveQueuePlayerResponse = new LeaveQueuePlayerResponse();
			Player player = PlayerCacheContainer.getPlayer(requestContent.getSessionId());
			
			if (player.isInGame()) {
				error(new PlayerError(PlayerError.PLAYER_ALREADY_IN_GAME), response);
				return;
			}
			
			PlayerCacheContainer.deletePlayer(player);
			leaveQueuePlayerResponse.setRequestAction(requestContent.getAction());
			
			response.setContentType("text/xml");
			response.getWriter().write(parser().parseResponse(leaveQueuePlayerResponse));
			response.getWriter().close();
		} catch (IOException ioException) {
			error(new ParserError(ParserError.STREAM_ERROR), response);
		} catch (ParserException parserException) {
			exception(parserException, response);
		}
	}

	@Override
	public void setRequest(AbstractRequest abstractRequest) {
		requestContent = (LeaveQueuePlayerRequest) abstractRequest;
	}

	@Override
	public Set<AbstractValidator> getValidators() {
		return validators;
	}

	@Override
	public IParser parser() {
		return parser;
	}
}